package vn.gq.udv.comic.fragment;

import com.polites.android.GestureImageView;
import com.polites.android.ZoomStateListener;

import vn.gq.udv.comic.IPagerActivity;
import vn.gq.udv.comic.R;
import vn.gq.udv.comic.ReaderActivity;
import vn.gq.udv.tab.BaseFragment;
import vn.gq.udv.utils.AndroidUtils;
import vn.gq.udv.utils.ImageFetcher;
import vn.gq.udv.utils.ImageWorker;
import vn.gq.udv.utils.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;


public class ReaderFragment extends BaseFragment implements ZoomStateListener {

	private static final String IMAGE_DATA_EXTRA = "extra_image_data";
	private static final String POSITION_EXTRA = "extra_position";
    private GestureImageView mImageView;
    private ImageFetcher mImageFetcher;
    private int mPosition = 0;
    private String mImageUrl = null;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle args = getArguments();
		if (args != null) {
			mImageUrl = args.getString(IMAGE_DATA_EXTRA);
			mPosition = args.getInt(POSITION_EXTRA);
		}
	}

	public static ReaderFragment newInstance(String imageUrl, int position) {
		ReaderFragment f = new ReaderFragment();
		Bundle args = new Bundle();
		args.putString(IMAGE_DATA_EXTRA, imageUrl);
		args.putInt(POSITION_EXTRA, position);
		f.setArguments(args);
		return f;
	}
	
	@Override
	public int getContainerId() {
		return 0;
	}

	@Override
	public int getLayoutId() {
		return R.layout.image_detail_fragment;
	}

	@Override
	public void createView() {
		 mImageView = (GestureImageView) mLayout.findViewById(R.id.imageView);
		 mImageView.setZoomStateListener(this);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (ReaderActivity.class.isInstance(getActivity())) {
			mImageFetcher = ((ReaderActivity) getActivity()).getImageFetcher();
            mImageFetcher.loadImage(mImageUrl, mImageView);
		}
		
		 // Pass clicks on the ImageView to the parent activity to handle
        if (OnClickListener.class.isInstance(getActivity()) && AndroidUtils.hasHoneycomb()) {
            mImageView.setOnClickListener((OnClickListener) getActivity());
        }
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mImageView != null) {
            // Cancel any pending image work
            ImageWorker.cancelWork(mImageView);
            mImageView.setImageDrawable(null);
        }
	}

	@Override
	public void onZoom(final boolean isZoom) {
		
		if (getActivity() instanceof IPagerActivity) {
			final ViewPager mViewPager = ((IPagerActivity) getActivity()).getViewPager();
			getActivity().runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					mViewPager.setPagingEnable(isZoom);
				}
			});
			
		}
	}

}
